package org.example.interceptor;

import com.sun.xml.internal.bind.v2.runtime.unmarshaller.Intercepter;
import lombok.extern.slf4j.Slf4j;
import org.example.bean.LoginUser;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/*
* 拦截器
* */
@Slf4j
public class MyInterceptor implements HandlerInterceptor {

    /*
    * 目标方法执行之前
    * */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        log.info("请求路径：{}", requestURI);

        HttpSession session = request.getSession();
        LoginUser userInfo = (LoginUser) session.getAttribute("userInfo");
        return true;
//        if(userInfo != null) {
//            // 有用户登录，则放行
//            return true;
//        }
//        // 返回数据给前端
//        // 设置响应内容类型为JSON
//        response.setContentType("application/json");
//        response.setCharacterEncoding("UTF-8");
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("code", "10002");
//        jsonObject.put("msg", "请先登录");
//        response.getWriter().write(jsonObject.toString());
//        return false;
    }

    /*
    * 目标方法执行之后
    * */
    @ResponseBody
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /*
    * 页面渲染以后
    * */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
